"""
2.导入创建的蓝图，并实现路由
"""
from flask import g
from flask import render_template,current_app, jsonify
from flask import request
from flask import session

from info import constants
from info.models import User, Category, News
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blue


#参数:页码/分类ID/每页数量--> 选填
@index_blue.route('/news_list')
def news_list():
	#一.获取参数(可选 可以给默认值)
	#cid没有1这个分类,如果是1,代表查询所有分类的最新数据
	cid = request.args.get('cid',1)
	page = request.args.get('page', 1)
	per_page = request.args.get('per_page', 10)

	#二.校验参数(验证数据类型)
	try:
		cid = int(cid)
		page = int(page)
		per_page = int(per_page)
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(erron=RET.DBERR,errmsg='参数有误')

	#三.逻辑处理(filter(可有可无).order_by(创建时间倒序).pagnate(第几页 每页数量 Flase))

	filters = [News.status == 0]
	if cid != 1:
		filters.append(News.category_id==cid)

	try:
		paninates = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
	except Exception as e:
		current_app.logger.error(e)
		return jsonify(erron=RET.DBERR,errmsg='数据库错误')

	#获取所有的新闻模型
	news_models = paninates.items


	#为了方便前端判断是否有下一页可以加载
	#获取分页的总页码
	total_page = paninates.pages

	#获取当前页码
	current_page = paninates.page



	news_list = []
	# 当news_models有值,遍历news_models本身,反之遍历else后面的数组
	for news in news_models:
		news_list.append(news.to_basic_dict())





	#四.返回数据
	data = {
		'news_list':news_list,
		'total_page': total_page,
        'current_page': current_page
	}
	return jsonify(errno=RET.OK,errmsg='成功',data=data)







# @index_blue.route('/')
# def index():
# 	# redis_store.set('image_code','EX7X')
# 	# session['name'] = 'itheima'
#
# 	# logging.fatal('fatal')
# 	# logging.error('error')
# 	# logging.warning('warning')
# 	# logging.info('info')
# 	# logging.debug('debug')
# 	redis_store.set('name','itheima')
# 	return 'hello----1111'


@index_blue.route('/')
@user_login_data
def index():
	# 这里会在登录后,再次调用.我们就可以根据session数据,获取用户信息
    #一.获取用户数据
	#读取session数据
	user = g.user

	# 二.分类数据 -->查询后 转字典返回
	news_models = None

	try:
		categorys = Category.query.all()
	except Exception as e:
		current_app.logger.error(e)


	categorys_list = []
	for category in categorys if categorys else []:
		categorys_list.append(category.to_dict())

	#三.点击排行数据--> 查询后 转字典返回
	try:
		#limit:不用加frist或者all.查询时会按照限制的数量进行返回
		news_models = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
	except Exception as e:
		current_app.logger.error(e)



	#模型数据转字典数据
	click_news_list = []
	# 当news_models有值,遍历news_models本身,反之遍历else后面的数组
	for news in news_models if news_models else []:
		click_news_list.append(news.to_basic_dict())





	#拼接返回数据字典
	data = {
		'user':user.to_index_dict() if user else None,
		'categorys_list':categorys_list,
		'click_news_list':click_news_list
	}

	return render_template('news/index.html',data=data)

@index_blue.route('/favicon.ico')
def get_favicon():
	return current_app.send_static_file('news/favicon.ico')
